import { showConfirm } from '@/utils/utils';
import { endFlowUsingPUT } from '@/services/ValueApprovelMgr';
import { Button, Card, Divider, Skeleton, Spin } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { useSize } from 'ahooks';

function useInterval(callback, delay) {
  const intervalId = React.useRef(null);
  const savedCallback = React.useRef(callback);
  React.useEffect(() => {
    savedCallback.current = callback;
  });
  React.useEffect(() => {
    const tick = () => savedCallback.current();
    if (typeof delay === 'number') {
      intervalId.current = window.setInterval(tick, delay);
      return () => window.clearInterval(intervalId.current);
    }
  }, [delay]);
  return intervalId.current;
}

function Index({
  children,
  action,
  loading,
  title,
  instanceId,
  submit,
  taskId,
  approvalState,
  url,
  viewUrl,
}) {
  const containerRef = useRef();
  const containerSize = useSize(containerRef);

  useEffect(() => {
    const theHead = document.getElementsByTagName('head').item(0);
    // 创建脚本的dom对象实例
    const myScript = document.createElement('script');
    myScript.src = process.env.oaUrl;
    myScript.type = 'text/javascript';
    myScript.defer = true;
    theHead.appendChild(myScript);
  }, []);

  // useEffect(() => {
  //   console.log('containerSize.height ==== ', containerSize.height);
  //   if (containerSize.height) {
  //     // eslint-disable-next-line no-unused-expressions
  //     window.cifioa?.sendMessage({
  //       type: 'height',
  //       height: containerSize.height,
  //     });
  //   }
  // }, [containerSize]);

  useEffect(() => {
    console.log(window.cifioa);
    if (window.cifioa) {
      console.log(containerSize.height, 'containerSize.height');
      // window.cifioa.sendMessage({
      //   type: 'height',
      //   height: containerSize.height,
      // });
      setTimeout(() => {
        window.cifioa.sendMessage({
          type: 'height',
          height: containerSize.height,
        });
      }, 1000);
    }
  }, [window.cifioa, containerSize.height]);

  // useInterval(() => {
  //   if (containerSize.height) {
  //     console.log(containerSize.height, 'containerSize.height');
  //     window.cifioa?.sendMessage({
  //       type: 'height',
  //       height: containerSize.height,
  //     });
  //   }
  // }, 1000);

  let hasOaInstanceId = false;
  let isEdit = false;

  // 是否已有oa流程实例
  if (instanceId && instanceId !== '') {
    hasOaInstanceId = true;
  }
  // 是否是修改状态 action=modify
  if (action && action === 'modify') {
    isEdit = true;
  }
  // 是否是oa驳回门户待办 taskId=xxx
  if (taskId) {
    isEdit = true;
  }
  const [discardLoading, setDiscardLoading] = useState(false);
  // 关闭
  function handleClose() {
    if (navigator.userAgent.includes('MSIE')) {
      // close IE
      if (navigator.userAgent.includes('MSIE 6.0')) {
        window.opener = null;
        window.close();
      } else {
        window.open('', '_top');
        window.top.close();
      }
    } else {
      // close chrome;It is effective when it is only one.
      window.opener = null;
      window.open('', '_self');
      window.close();
    }
  }
  // 废弃
  function handleDiscard() {
    showConfirm(
      () => {
        endFlowUsingPUT({
          params: {
            instanceId,
          },
        })
          .then(result => {
            setDiscardLoading(true);
            if (result && result.code === 1 && url) {
              window.location.href = url;
            }
          })
          .then(() => setDiscardLoading(false));
      },
      '是否要废弃该流程?',
      '确定后将作废该流程后退出审批页面',
    );
  }
  // 查看审批
  function handleViewApprove() {
    if (viewUrl) {
      window.location.href = viewUrl;
    }
  }

  // 返回修改
  function handleReturnModify() {
    if (url) {
      handleClose();
      window.open(url);
    }
  }

  if (isEdit) {
    return (
      <div className="approve-box" style={{ padding: '20px 50px' }}>
        <Spin spinning={loading}>
          {/* 标题 */}
          <div className="approve-box-title">{title}</div>
          {/* 审批内容 */}
          <Card className="approve-box-content">
            {/* 审批内容一级标题 */}
            <div className="approve-box-content-title">
              <div className="approve-box-content-title-text">审批内容</div>
              <Divider />
            </div>
            {loading ? <Skeleton active /> : children}
            {/* 底部操作 */}
            <footer className="approve-box-content-footer">
              <Button type="primary" {...submit}>
                提交到OA审批
              </Button>
              <Button onClick={handleReturnModify}>返回修改</Button>
              {hasOaInstanceId && (
                <Button type="primary" onClick={handleViewApprove}>
                  查看审批
                </Button>
              )}
              {hasOaInstanceId && (approvalState === 'reject' || approvalState === 'recall') && (
                <Button onClick={handleDiscard} loading={discardLoading}>
                  废弃流程
                </Button>
              )}
              <Button className="red-button" onClick={handleClose}>
                关闭
              </Button>
            </footer>
          </Card>
        </Spin>
      </div>
    );
  }
  return (
    <div className="approve-box" ref={containerRef}>
      {/* 审批内容 */}
      <div className="approve-box-content">
        <Spin spinning={loading}>{loading ? <Skeleton active /> : children}</Spin>
      </div>
    </div>
  );
}

export default Index;
